package com.zsw.dubbo.register;

import java.io.IOException;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ProtocolConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.alibaba.dubbo.config.ServiceConfig;
import com.zsw.dubbo.service.DemoService;
import com.zsw.dubbo.service.DemoServiceImp;

public class ZookeeperRegister {

	public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
//		ZookeeperRegister.init();
		ZooKeeper z = new ZooKeeper("17.18.2.65:2181", 30000000, new Watcher() {
			@Override
			public void process(WatchedEvent event) {
			}
		});
		Watcher watcher = new Watcher() {
			@Override
			public void process(WatchedEvent event) {
				try {
					z.exists("/seal_group/com.kfx.seal.dubbo.service.DemoService/providers",this);
					System.out.println(z.getChildren("/seal_group/com.kfx.seal.dubbo.service.DemoService/providers", this));
				} catch (KeeperException e) {
					e.printStackTrace();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println(event.getType());
				System.out.println(event.getWrapper());
				System.out.println(event.getState());
				System.out.println("-------------");
			}
		};
		z.exists("/seal_group/com.kfx.seal.dubbo.service.DemoService/providers", watcher);
		z.getChildren("/seal_group/com.kfx.seal.dubbo.service.DemoService/providers", watcher);
		try {
			System.in.read();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static void init() {

		// 当前配置
		ApplicationConfig application = new ApplicationConfig();
		application.setName("fps");

		// 连接注册中心
		RegistryConfig registry = new RegistryConfig();
		registry.setAddress("zookeeper://47.88.17.106:2181");
		registry.setGroup("seal_group");

		// 服务提供者协议配置
		ProtocolConfig protocol = new ProtocolConfig();
		protocol.setName("dubbo");
		protocol.setPort(20885);

//		ProviderConfig ccc = new ProviderConfig();
		// 注意：ServiceConfig为重对象，内部封装了与注册中心的连接，以及开启服务端口

		// 服务提供者暴露服务配置
		ServiceConfig<DemoService> service = new ServiceConfig<DemoService>();
		service.setApplication(application);
		service.setRegistry(registry);
		service.setProtocol(protocol);
		service.setInterface(DemoService.class);
		service.setRef(new DemoServiceImp());
		// 暴露及注册服务
		service.export();
		
		try {
			System.in.read();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
